import i18n from './i18n.js'
import Store from '../store'
import Currency from './currency.js'
import * as TWEEN from "@tweenjs/tween.js";
const utils = {
	formatTime: function(time) {
		if (time < 0) {
			return false
		}
		time = Number(time)
		let d = parseInt(time / 60 / 60 / 24);
		// d = d < 10 ? '0' + d : d;
		let h = parseInt((time / 60 / 60) % 24);
		h = h < 10 ? '0' + h : h;
		let m = parseInt((time / 60) % 60);
		m = m < 10 ? '0' + m : m;
		let s = parseInt(time % 60);
		s = s < 10 ? '0' + s : s;
		// console.log('time', time);
		return {
			days: d,
			h: h.toString(),
			m: m.toString(),
			s: s.toString(),
		};
	},
	formatStr(num) {
		return num.toString().replace(/\d+/, function(n) { // 先提取整数部分
			return n.replace(/(\d)(?=(\d{3})+$)/g, function($1) {
				return $1 + ",";
			});
		})
	},
	formatPhone(num) {
		if (!num) return ''
		if (num <= 11) {
			return num.substring(0, 3) + "****" + num.substring(7);
		} else {
			return num.substring(0, 3) + "****" + num.substring(num.length - 3);
		}
	},
	// 金额保留后两位小鼠
	formatMoney(num) {
		if (!num) return ''
		num = num.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符  
		num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的  
		num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
		num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数 
		return num
	},
	isMobile: function() {
		let userAgentInfo = navigator.userAgent;
		let Agents = [
			"Android",
			"iPhone",
			"SymbianOS",
			"Windows Phone",
			"iPad",
			"iPod",
		];
		let getArr = Agents.filter((i) => userAgentInfo.includes(i));
		return getArr.length ? true : false;
	},
	encryptionHash(str) {
		if (!str) return ''
		let newStr = str.toString()
		return newStr.substr(0, 8) + "..." + newStr.substr(str.length - 8)
	},
	copy(context) {
		// console.log('context', context);
		// 创建输入框元素
		let oInput = document.createElement('input');
		// 将想要复制的值
		oInput.value = context;
		// 页面底部追加输入框
		document.body.appendChild(oInput);
		// 选中输入框
		oInput.select();
		// 执行浏览器复制命令
		document.execCommand('Copy');
		// 复制后移除输入框
		oInput.remove();
	},
	saveImg(selector, name) {
		var img = document.querySelector(selector)
		var url = img.src
		var a = document.createElement('a')
		var event = new MouseEvent('click')
		a.download = (name || 'download') + '.png'
		// console.log('url::', a);
		a.href = url
		a.dispatchEvent(event)
	},
	mobileSaveImg(Url) {
		var blob = new Blob([''], {
			type: 'application/octet-stream'
		})
		var url = URL.createObjectURL(blob)
		var a = document.createElement('a')
		a.href = Url
		// a.download = Url.replace(/(.*\/)*([^.]+.*)/gi, '$2').split('?')[0];
		a.download = 'download.png'
		var e = document.createEvent('MouseEvents')
		e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
		a.dispatchEvent(e)
		URL.revokeObjectURL(url)
	},
	baseToBlob(url) {
		var arr = url.split(',');
		var mime = arr[0].match(/:(.*?);/)[1];
		var bstr = atob(arr[1]);
		var n = bstr.length;
		var u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n)
		}
		return new Blob([u8arr], {
			type: mime
		})
	},

	blobToFile(theBlob, fileName) {
		let files = new File([theBlob], fileName, {
			type: 'image/jpeg'
		})
		theBlob.lastModifiedDate = new Date();
		theBlob.name = fileName;
		return files;
	},
	isBase64(str) {
		// Base64编码的正则表达式
		var base64reg = /^(?:[A-Za-z0-9+/]{4})*?(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
		// 判断字符串是否匹配Base64编码的正则表达式
		return base64reg.test(str);
	},
	isSafari() {
		return /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
	},
	getUserLang() {
		return (navigator.browserLanguage || navigator.language || navigator.userLanguage).substring(0, 2);
	},
	changeLanguage(item) {
		i18n.locale = item.locale
		Store.commit('upDataLang', item.locale)
		localStorage.setItem('lang', item.locale)
	},
	getUnit() {
		let unit = localStorage.getItem("unit");
		let symbol = "$";
		if (unit) {
			let n = Currency.find(i => i.name == unit);
			symbol = n ? n.symbol : "$"
		}
		return symbol
	},
	// 16进制
	str16hex(str) {
		var dec = str.toString().split(''),
			sum = [],
			hex = [],
			i, s
		// console.log('dec', dec);
		while (dec.length) {
			s = 1 * dec.shift()
			for (i = 0; s || i < sum.length; i++) {
				s += (sum[i] || 0) * 10
				sum[i] = s % 16
				s = (s - sum[i]) / 16
			}
		}
		while (sum.length) {
			hex.push(sum.pop().toString(16))
		}
		return hex.join('')
	},
	accMul(arg1, arg2) {
		var m = 0,
			s1 = arg1.toString(),
			s2 = arg2.toString();
		try {
			m += s1.split(".")[1].length
		} catch (e) {}
		try {
			m += s2.split(".")[1].length
		} catch (e) {}
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
	},
	/**
	 * @param {Number} len uuid的长度
	 * @param {Boolean} firstU 将返回的首字母置为"u"
	 * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
	 */
	guid(len = 16, firstU = true, radix = null) {
		const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
		const uuid = []
		radix = radix || chars.length

		if (len) {
			// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
			for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
		} else {
			let r
			// rfc4122标准要求返回的uuid中,某些位为固定的字符
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
			uuid[14] = '4'

			for (let i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
				}
			}
		}
		// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
		if (firstU) {
			uuid.shift()
			return `u${uuid.join('')}`
		}
		return uuid.join('')
	},
	/**
	 * @description 取一个区间数
	 * @param {Number} min 最小值
	 * @param {Number} max 最大值
	 */
	random(min, max) {
		if (min >= 0 && max > 0 && max >= min) {
			const gab = max - min + 1
			return Math.floor(Math.random() * gab + min)
		}
		return 0
	},
	/**
	 * @description 去除空格
	 * @param String str 需要去除空格的字符串
	 * @param String pos both(左右)|left|right|all 默认both
	 */
	trim(str, pos = 'both') {
		str = String(str)
		if (pos == 'both') {
			return str.replace(/^\s+|\s+$/g, '')
		}
		if (pos == 'left') {
			return str.replace(/^\s*/, '')
		}
		if (pos == 'right') {
			return str.replace(/(\s*$)/g, '')
		}
		if (pos == 'all') {
			return str.replace(/\s+/g, '')
		}
		return str
	},
	/**
	 * @description 深度克隆
	 * @param {object} obj 需要深度克隆的对象
	 * @returns {*} 克隆后的对象或者原值（不是对象）
	 */
	deepClone(obj) {
		// 对常见的“非”值，直接返回原来值
		if ([null, undefined, NaN, false].includes(obj)) return obj
		if (typeof obj !== 'object' && typeof obj !== 'function') {
			// 原始类型直接返回
			return obj
		}
		const o = test.array(obj) ? [] : {}
		for (const i in obj) {
			if (obj.hasOwnProperty(i)) {
				o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
			}
		}
		return o
	},
	/**
	 * @num 数字
	 * @digits 保留几位小数
	 */
	truncateDecimals(num, digits) {
		var numStr = num.toString();
		var decimalIndex = numStr.indexOf('.');
		// console.log('decimalIndex', num, decimalIndex);
		if (decimalIndex !== -1) {
			// Truncate decimal part to specified digits
			numStr = numStr.substr(0, decimalIndex + 1 + digits);
		}

		return parseFloat(numStr);
	},
	// 数据线性动画
	interpolate(data) {
		if (!data.length) return [];
		const step = 0.25;
		const list = [data[0]];
		for (let i = 1; i < data.length; i++) {
			const prev = data[i - 1];
			const current = data[i];
			let progress = step;
			while (progress <= 1) {
				const pointer = TWEEN.Easing.Cubic.InOut(progress);
				const value = TWEEN.Interpolation.Utils.Linear(
					Number(prev.value),
					Number(current.value),
					pointer
				);
				const time = TWEEN.Interpolation.Utils.Linear(
					prev.time,
					current.time,
					pointer
				);
				list.push({
					price: String(value),
					timestamp: Math.round(time),
					time: Math.round(time),
					value: String(value),
				});
				progress += step;
			}
		}
		return list;
	}

}

export default utils